// UI交互和事件处理功能
function initUIFunctions(app) {
    // 扩展HttpRequestTool类，添加UI相关方法
    Object.assign(app, {
        showModal(title, content) {
            document.getElementById('modal-title').textContent = title;
            document.getElementById('modal-body').innerHTML = content;
            document.getElementById('modal-overlay').classList.add('show');
        },

        hideModal() {
            document.getElementById('modal-overlay').classList.remove('show');
        },

        showMessage(message) {
            // 简单的消息提示
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.textContent = message;
            toast.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: var(--success-color);
                color: white;
                padding: 12px 20px;
                border-radius: 4px;
                z-index: 10000;
                animation: slideInRight 0.3s ease-out;
            `;

            document.body.appendChild(toast);

            setTimeout(() => {
                toast.remove();
            }, 3000);
        },

        initJsonEditor() {
            const bodyTextarea = document.getElementById('body-textarea');
            if (!bodyTextarea) return;

            // 自动括号匹配
            bodyTextarea.addEventListener('keydown', (e) => {
                this.handleJsonEditorKeydown(e);
            });

            // 添加格式化按钮
            this.addJsonFormatButton();
        },

        handleJsonEditorKeydown(e) {
            const textarea = e.target;
            const { selectionStart, selectionEnd, value } = textarea;

            // 自动括号匹配
            const bracketPairs = {
                '{': '}',
                '[': ']',
                '"': '"',
                '(': ')'
            };

            if (bracketPairs[e.key]) {
                e.preventDefault();
                const before = value.substring(0, selectionStart);
                const after = value.substring(selectionEnd);
                const closingBracket = bracketPairs[e.key];

                // 对于引号，检查是否需要自动配对
                if (e.key === '"') {
                    const beforeQuoteCount = (before.match(/"/g) || []).length;
                    if (beforeQuoteCount % 2 === 1) {
                        // 奇数个引号，不自动配对
                        textarea.value = before + e.key + after;
                        textarea.setSelectionRange(selectionStart + 1, selectionStart + 1);
                        return;
                    }
                }

                textarea.value = before + e.key + closingBracket + after;
                textarea.setSelectionRange(selectionStart + 1, selectionStart + 1);
            }

            // 自动缩进
            if (e.key === 'Enter') {
                e.preventDefault();
                const before = value.substring(0, selectionStart);
                const after = value.substring(selectionEnd);
                const lines = before.split('\n');
                const currentLine = lines[lines.length - 1];

                // 计算当前行的缩进
                const indent = currentLine.match(/^\s*/)[0];
                let newIndent = indent;

                // 如果当前行以 { 或 [ 结尾，增加缩进
                if (currentLine.trim().endsWith('{') || currentLine.trim().endsWith('[')) {
                    newIndent += '  ';
                }

                // 如果下一个非空字符是 } 或 ]，在中间插入额外的缩进行
                const nextChar = after.trim().charAt(0);
                if (nextChar === '}' || nextChar === ']') {
                    textarea.value = before + '\n' + newIndent + '\n' + indent + after;
                    textarea.setSelectionRange(selectionStart + newIndent.length + 1, selectionStart + newIndent.length + 1);
                } else {
                    textarea.value = before + '\n' + newIndent + after;
                    textarea.setSelectionRange(selectionStart + newIndent.length + 1, selectionStart + newIndent.length + 1);
                }
            }

            // Tab键缩进
            if (e.key === 'Tab') {
                e.preventDefault();
                const before = value.substring(0, selectionStart);
                const after = value.substring(selectionEnd);

                if (e.shiftKey) {
                    // Shift+Tab 减少缩进
                    const lines = before.split('\n');
                    const currentLine = lines[lines.length - 1];
                    if (currentLine.startsWith('  ')) {
                        lines[lines.length - 1] = currentLine.substring(2);
                        textarea.value = lines.join('\n') + after;
                        textarea.setSelectionRange(selectionStart - 2, selectionStart - 2);
                    }
                } else {
                    // Tab 增加缩进
                    textarea.value = before + '  ' + after;
                    textarea.setSelectionRange(selectionStart + 2, selectionStart + 2);
                }
            }
        },

        addJsonFormatButton() {
            const bodyPanel = document.getElementById('body-panel');
            if (!bodyPanel) return;

            // 检查是否已经添加了格式化按钮
            if (bodyPanel.querySelector('.json-format-btn')) return;

            const formatButton = document.createElement('button');
            formatButton.className = 'btn btn-small json-format-btn';
            formatButton.innerHTML = '<span class="icon">🎨</span> 格式化JSON';
            formatButton.type = 'button';
            formatButton.style.marginTop = '8px';

            formatButton.addEventListener('click', () => {
                this.formatJsonContent();
            });

            const bodyEditor = bodyPanel.querySelector('.body-editor');
            bodyEditor.appendChild(formatButton);
        },

        formatJsonContent() {
            const textarea = document.getElementById('body-textarea');
            const content = textarea.value.trim();

            if (!content) {
                this.showMessage('请先输入JSON内容');
                return;
            }

            try {
                const parsed = JSON.parse(content);
                const formatted = JSON.stringify(parsed, null, 2);
                textarea.value = formatted;
                this.showMessage('JSON格式化成功');
            } catch (error) {
                this.showMessage('JSON格式错误，无法格式化');
            }
        },

        handleKeyboardShortcuts(e) {
            // ESC键关闭面板
            if (e.key === 'Escape') {
                this.hideModal();
                return;
            }

            if (e.ctrlKey || e.metaKey) {
                switch (e.key) {
                    case 'n':
                        e.preventDefault();
                        this.createNewTab();
                        break;
                    case 't':
                        e.preventDefault();
                        this.copyCurrentTimeToClipboard();
                        break;
                    case 'w':
                        e.preventDefault();
                        this.closeTab(this.currentTab);
                        break;
                    case 's':
                        e.preventDefault();
                        this.saveCurrentTab();
                        break;
                    case 'Enter':
                        e.preventDefault();
                        this.sendRequest();
                        break;
                    case 'f':
                        // Ctrl+F 格式化JSON (仅在请求体编辑器中)
                        if (e.target.id === 'body-textarea') {
                            e.preventDefault();
                            this.formatJsonContent();
                        }
                        break;
                    case 'm':
                        e.preventDefault();
                        // 检查面板是否已显示，如果已显示则关闭，否则打开
                        const modalOverlay = document.getElementById('modal-overlay');
                        if (modalOverlay.classList.contains('show')) {
                            this.hideModal();
                        } else {
                            this.showLoadTabDialog();
                        }
                        break;
                }
            }
        },
        
        // 将当前时间复制到剪贴板
        copyCurrentTimeToClipboard() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            
            const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            
            // 复制到剪贴板
            navigator.clipboard.writeText(formattedTime)
                .then(() => {
                    this.showMessage(`时间已复制: ${formattedTime}`);
                })
                .catch(err => {
                    this.showMessage('复制失败，请手动复制');
                    console.error('复制失败:', err);
                });
        }
    });

    // 添加CSS动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        .url-history-list {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .history-item {
            padding: 8px 12px;
            border-bottom: 1px solid var(--border-light);
            cursor: pointer;
            font-size: 13px;
        }
        
        .history-item:hover {
            background: var(--bg-tertiary);
        }
        
        .history-item:last-child {
            border-bottom: none;
        }
    `;
    document.head.appendChild(style);

    // 初始化JSON编辑器
    if (app.initJsonEditor) {
        app.initJsonEditor();
    }
    
    // 初始化键盘快捷键
    if (app.handleKeyboardShortcuts) {
        document.addEventListener('keydown', (e) => app.handleKeyboardShortcuts(e));
    }
}

// 导出函数以便在其他文件中使用
window.initUIFunctions = initUIFunctions;